#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <ctype.h>



int main(int argc, char *argv[])
{
    int lfd,cfd;
    int ret,i;
    char name[200]="xiaoming";
    char passwd[200]="123";
    
	struct sockaddr_in srv_addr;		// 创建服务器地址结构,初始化
	
	srv_addr.sin_family = AF_INET;
	srv_addr.sin_port = htons(8888);
	srv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    

    //1.创建套接字
    lfd = socket(AF_INET , SOCK_STREAM,0);
    if(lfd == -1)
    {
        perror("socket");
        return -1;
    }
    //2.绑定服务器IP和端口号
    if(bind(lfd,(struct sockaddr*)&srv_addr, sizeof(srv_addr))==-1)
    {
    	perror("bind");
    	return -1;
    }
    //3.设置监听上限
    if(listen(lfd,5)==-1)
    {
    	perror("listen");
    	return -1;
    }
    printf("服务器等待客户端链接...\n");
    
    //4.阻塞等待客户端连接请求
	cfd = accept(lfd,NULL, NULL);
		 if(cfd == -1)
    {
    	perror("accept");
    	return -1;
    }
	printf("链接成功\n");
	while (1) 
	{
	// 5.read() 读取客户端发送数据
	char buf[20];
	char recv_name[20];
	char recv_passwd[20];
	
	read(cfd, buf, sizeof(buf));
	printf("现在的状态是：%s\n", buf);
	if(strcmp(buf,"login")== 0)
	{
		read(cfd, recv_name, sizeof(recv_name));
		read(cfd, recv_passwd, sizeof(recv_passwd));
		//printf("姓名：%s\t密码：%s登陆成功\n",name,passwd);
		if((strcmp(name, recv_name)==0)&&(strcmp(passwd, recv_passwd)==0))
		{
			strcpy(buf,"登陆成功");
			write(cfd, buf, sizeof(buf));
		}
		else
		{
			strcpy(buf,"登陆失败");
			write(cfd, buf, sizeof(buf));
		}
	}
	else
	{
		read(cfd, recv_name, sizeof(recv_name));
		read(cfd, recv_passwd, sizeof(recv_passwd));
		printf("姓名：%s\t密码：%s注册成功\n",recv_name,recv_passwd);
			strcpy(name,recv_name);
			strcpy(passwd,recv_passwd);
		
			strcpy(buf,"注册成功");
			write(cfd, buf, sizeof(buf));
		
	}
	
  }
}

